package org.mspring.mlog.web.module.web.widget;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.mspring.platform.config.ConfigService;
import org.mspring.platform.utils.StringUtils;
import org.mspring.platform.web.freemarker.widget.stereotype.Widget;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

/**
 *
 * @author Gao Youbo
 * @since 2013年9月23日
 */
@Widget
@RequestMapping("/widget/common")
public class Widget_CommonWidget extends Widget_AbstractWidget {

    @Autowired
    private ConfigService configService;

    /**
     * 分类列表
     *
     * @param tpl
     * @param request
     * @param response
     * @param model
     * @return
     * @throws java.io.IOException
     */
    @RequestMapping("/menu")
    public String list(@RequestParam(required = false, defaultValue = "/widget/common/menu") String tpl, HttpServletRequest request, HttpServletResponse response, Model model) throws IOException {
        List<String> menus = new ArrayList<>();
        String url = configService.getConfig("siteurl");

        // 用户配置menu
        String menuString = configService.getConfig("menu");
        if (StringUtils.isNotBlank(menuString)) {
            StringReader sr = new StringReader(menuString);
            BufferedReader reader = new BufferedReader(sr);
            String menu = "";
            while (StringUtils.isNotBlank(menu = reader.readLine())) {
                menu = menu.replaceAll("%base%", url);
                menus.add(menu);
            }
        }
        model.addAttribute("menus", menus);
        return "skin:" + tpl;
    }
}
